<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言最近在学习node，有用pug模板引擎来实现简单网站跟后端的搭建，搭建过程中使用到了KOA框架；KOA框架本身就比较简洁易用，相较于express是一个更加轻量级的框架，所有的功能都通过插件来实现。而且本身的源码也十分简洁，只有4个JS文件，因此就想以新手的角度分析并学习一下KOA框架源码与设计理念。 KOA用法1234567891011121314const Koa &#x3D; require(&#39;k">
<meta property="og:type" content="article">
<meta property="og:title" content="KOA源码">
<meta property="og:url" content="http://example.com/2021/05/19/node/koa%E6%BA%90%E7%A0%81/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言最近在学习node，有用pug模板引擎来实现简单网站跟后端的搭建，搭建过程中使用到了KOA框架；KOA框架本身就比较简洁易用，相较于express是一个更加轻量级的框架，所有的功能都通过插件来实现。而且本身的源码也十分简洁，只有4个JS文件，因此就想以新手的角度分析并学习一下KOA框架源码与设计理念。 KOA用法1234567891011121314const Koa &#x3D; require(&#39;k">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-05-19T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-03T08:20:03.455Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="Koa框架">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/05/19/node/koa%E6%BA%90%E7%A0%81/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>KOA源码 | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/05/19/node/koa%E6%BA%90%E7%A0%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          KOA源码
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-05-19 12:18:39" itemprop="dateCreated datePublished" datetime="2021-05-19T12:18:39+08:00">2021-05-19</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:20:03" itemprop="dateModified" datetime="2021-11-03T16:20:03+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>最近在学习node，有用pug模板引擎来实现简单网站跟后端的搭建，搭建过程中使用到了KOA框架；KOA框架本身就比较简洁易用，相较于express是一个更加轻量级的框架，所有的功能都通过插件来实现。而且本身的源码也十分简洁，只有4个JS文件，因此就想以新手的角度分析并学习一下KOA框架源码与设计理念。</p>
<h1 id="KOA用法"><a href="#KOA用法" class="headerlink" title="KOA用法"></a>KOA用法</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"></span><br><span class="line">app.use(<span class="function">(<span class="params">ctx, next</span>) =&gt;</span> &#123;</span><br><span class="line">  ctx.body = <span class="string">'Hello World'</span>;</span><br><span class="line">&#125;);</span><br><span class="line">app.listen(<span class="number">3000</span>); </span><br><span class="line"></span><br><span class="line"><span class="comment">//下面是不用框架时的用法</span></span><br><span class="line"><span class="keyword">let</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>)</span><br><span class="line"><span class="keyword">let</span> server = http.createServer(<span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">  res.end(<span class="string">'hello world'</span>)</span><br><span class="line">&#125;)</span><br><span class="line">server.listen(<span class="number">4000</span>)</span><br></pre></td></tr></table></figure>

<p>对比发现，相对原生，koa多了两个实例上的use、listen方法，和use回调中的ctx、next两个参数。这四个不同，几乎就是koa的全部了，也是这四个不同让koa如此强大。</p>
<h2 id="listen"><a href="#listen" class="headerlink" title="listen"></a>listen</h2><p>本质上是http的语法糖，实际上还是用了http.createServer()，然后监听了一个端口。</p>
<h2 id="ctx"><a href="#ctx" class="headerlink" title="ctx"></a>ctx</h2><p>利用 <strong>上下文(context)</strong> 机制，将原来的req,res对象合二为一，并进行了大量拓展,使开发者可以方便的使用更多属性和方法，大大减少了处理字符串、提取信息的时间，免去了许多引入第三方包的过程。(例如ctx.query、ctx.path等)</p>
<h2 id="use"><a href="#use" class="headerlink" title="use"></a>use</h2><p>koa的核心 —— <strong>中间件（middleware）</strong>机制。解决了异步编程中回调地狱的问题，基于<a href="https://juejin.im/post/6844903583234834445" target="_blank" rel="noopener">Promise</a>，利用 <strong>洋葱模型</strong> 思想，使嵌套的、纠缠不清的代码变得清晰、明确，并且可拓展，可定制，借助许多第三方中间件，可以使精简的koa更加全能（例如koa-router，实现了路由）。其原理主要是一个极其精妙的 <strong>compose</strong> 函数。在使用时，用 <strong>next()</strong> 方法，从上一个中间件跳到下一个中间件。</p>
<h2 id="实现思路"><a href="#实现思路" class="headerlink" title="实现思路"></a>实现思路</h2><p>application.js为入口文件；context.js是上下文对象相关；request.js是请求对象相关；response.js是响应对象相关。</p>
<p>整体的原理无非就是use的时候拿到一个回调函数，listen的时候执行这个函数。此外，use回调函数的参数ctx拓展了很多功能，这个ctx其实就是原生的req、res经过一系列处理产生的。同样，use的时候可以拿到多个回调函数，用户使用第二个参数next()跳到下一个，并把多个use的回调函数按照规则顺序执行。</p>
<p>难点只有两个：一个是如何将原生req和res加工成ctx，另一个是如何实现中间件。</p>
<p>1、ctx其实就是一个上下文对象，request和response两个文件用来拓展属性，context文件实现代理。</p>
<p>2、源码中的中间件由一个中间件执行模块koa-compose实现。</p>
<h2 id="源码简介"><a href="#源码简介" class="headerlink" title="源码简介"></a>源码简介</h2><h3 id="application-js"><a href="#application-js" class="headerlink" title="application.js"></a>application.js</h3><p>application.js是koa的入口文件，它向外导出了创建class实例的构造函数，它继承了events，这样就会赋予框架事件监听和事件触发的能力。application还暴露了一些常用的api，比如toJSON、listen、use等等。</p>
<p>listen的实现原理其实就是对http.createServer进行了一个封装，重点是这个函数中传入的callback，它里面包含了中间件的合并，上下文的处理，对res的特殊处理。</p>
<p>use是收集中间件，将多个中间件放入一个缓存队列中，然后通过koa-compose这个插件进行递归组合调用这一些列的中间件。</p>
<h3 id="context-js"><a href="#context-js" class="headerlink" title="context.js"></a>context.js</h3><p>这部分就是koa的应用上下文ctx,其实就一个简单的对象暴露，里面的重点在delegate，这个就是代理，这个就是为了开发者方便而设计的，比如我们要访问ctx.repsponse.status但是我们通过delegate，可以直接访问ctx.status访问到它。</p>
<h3 id="request-js、response-js"><a href="#request-js、response-js" class="headerlink" title="request.js、response.js"></a>request.js、response.js</h3><p>这两部分就是对原生的res、req的一些操作了，大量使用es6的get和set的一些语法，去取headers或者设置headers、还有设置body等等。</p>
<h2 id="功能模块"><a href="#功能模块" class="headerlink" title="功能模块"></a>功能模块</h2><h3 id="模块一"><a href="#模块一" class="headerlink" title="模块一"></a>模块一</h3><p><strong>封装node http server和创建Koa类构造函数</strong>。对http server进行了简单的封装和创建了一个可以生成koa实例的类class，这个类里还实现了app.use用来注册中间件和注册回调函数，app.listen用来开启服务器实例并传入callback回调函数；主要还是搭了一个简陋的架子。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Application</span> </span>&#123;    </span><br><span class="line">    <span class="keyword">constructor</span>() &#123;        </span><br><span class="line">        <span class="keyword">this</span>.callbackFunc;</span><br><span class="line">    &#125;</span><br><span class="line">    listen(port) &#123;        </span><br><span class="line">        <span class="keyword">let</span> server = http.createServer(<span class="keyword">this</span>.callback());</span><br><span class="line">        server.listen(port);</span><br><span class="line">    &#125;</span><br><span class="line">    use(fn) &#123;</span><br><span class="line">        <span class="keyword">this</span>.callbackFunc = fn;</span><br><span class="line">    &#125;</span><br><span class="line">    callback() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.callbackFunc(req, res);</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">module</span>.exports = Application;</span><br></pre></td></tr></table></figure>

<h3 id="模块二"><a href="#模块二" class="headerlink" title="模块二"></a>模块二</h3><p><strong>构造request、response、context对象</strong>。其中，context就是我们平时写koa代码时的ctx，它相当于一个全局的koa实例上下文this，它连接了request、response两个功能模块，并且暴露给koa的实例和中间件等回调函数的参数中，起到承上启下的作用。</p>
<p>request、response两个功能模块分别对node的原生request、response进行了一个功能的封装，使用了getter和setter属性，基于node的对象req/res对象封装koa的request/response对象。</p>
<p>第一步，我们要实现上下文对象ctx，里面绑定了很多请求和相应相关的数据和方法，例如ctx.path、ctx.query、ctx.body()等等。思路是：用户调用use方法时，把这个回调fn存起来，创建一个createContext函数用来创建上下文，创建一个handleRequest函数用来处理请求，用户listen时将handleRequest放进createServer回调中，在函数内调用fn并将上下文对象传入，用户就得到了ctx。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Koa</span> <span class="keyword">extends</span> <span class="title">EventEmitter</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span> () &#123;</span><br><span class="line">    <span class="keyword">super</span>()</span><br><span class="line">    <span class="keyword">this</span>.fn</span><br><span class="line">    <span class="keyword">this</span>.context = context <span class="comment">// 将三个模块保存，全局的放到实例上</span></span><br><span class="line">    <span class="keyword">this</span>.request = request</span><br><span class="line">    <span class="keyword">this</span>.response = response</span><br><span class="line">  &#125;</span><br><span class="line">  use (fn) &#123;</span><br><span class="line">    <span class="keyword">this</span>.fn = fn</span><br><span class="line">  &#125;</span><br><span class="line">  createContext(req, res)&#123; <span class="comment">// 这是核心，创建ctx</span></span><br><span class="line">    <span class="comment">// 使用Object.create方法是为了继承this.context但在增加属性时不影响原对象;继承属性，且不影响原对象</span></span><br><span class="line">    <span class="keyword">const</span> ctx = <span class="built_in">Object</span>.create(<span class="keyword">this</span>.context)</span><br><span class="line">    <span class="keyword">const</span> request = ctx.request = <span class="built_in">Object</span>.create(<span class="keyword">this</span>.request)</span><br><span class="line">    <span class="keyword">const</span> response = ctx.response = <span class="built_in">Object</span>.create(<span class="keyword">this</span>.response)</span><br><span class="line">    <span class="comment">// 下面的操作是为了把ctx中的属性与request、response中的属性联系起来，其实就是将后两者中定义的方法挂载到ctx上</span></span><br><span class="line">    <span class="comment">//这样，我们后续就可以在ctx中用简洁的写法来访问各种属性了</span></span><br><span class="line">    ctx.req = request.req = response.req = req</span><br><span class="line">    ctx.res = request.res = response.res = res</span><br><span class="line">    request.ctx = response.ctx = ctx</span><br><span class="line">    request.response = response</span><br><span class="line">    response.request = request</span><br><span class="line">    <span class="keyword">return</span> ctx</span><br><span class="line">  &#125;</span><br><span class="line">  handleRequest(req,res)&#123; <span class="comment">// 创建一个处理请求的函数</span></span><br><span class="line">    <span class="keyword">let</span> ctx = <span class="keyword">this</span>.createContext(req, res) <span class="comment">// 创建ctx</span></span><br><span class="line">    <span class="keyword">this</span>.fn(ctx) <span class="comment">// 调用用户给的回调，把ctx还给用户使用。</span></span><br><span class="line">    res.end(ctx.body) <span class="comment">// ctx.body用来输出到页面，后面会说如何绑定数据到ctx.body</span></span><br><span class="line">  &#125;</span><br><span class="line">  listen (...args) &#123;</span><br><span class="line">    <span class="keyword">let</span> server = http.createServer(<span class="keyword">this</span>.handleRequest.bind(<span class="keyword">this</span>))<span class="comment">// 这里使用bind调用，以防this丢失</span></span><br><span class="line">    server.listen(...args)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第二步：这个时候，我们可以直接通过ctx.request.req.url或者ctx.response.req.url来获取想要的值，但还是利用的原生属性方法，此时我们基于node的对象req/res对象封装koa的request/response对象；其实两者的本质都是一样的封装。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//request.js</span></span><br><span class="line"><span class="keyword">let</span> url = <span class="built_in">require</span>(<span class="string">'url'</span>)</span><br><span class="line"><span class="keyword">let</span> request = &#123;</span><br><span class="line">  <span class="keyword">get</span> url() &#123; <span class="comment">// 这样就可以用ctx.request.url上取值了，不用通过原生的req</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.req.url</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="keyword">get</span> path() &#123;</span><br><span class="line">    <span class="keyword">return</span> url.parse(<span class="keyword">this</span>.req.url).pathname</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="keyword">get</span> query() &#123;</span><br><span class="line">    <span class="keyword">return</span> url.parse(<span class="keyword">this</span>.req.url).query</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 。。。。。。</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">module</span>.exports = request</span><br><span class="line"></span><br><span class="line"><span class="comment">//response.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    <span class="keyword">get</span> body() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>._body;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">set</span> body(data) &#123;</span><br><span class="line">        <span class="keyword">this</span>._body = data;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">get</span> status() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.res.statusCode;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">set</span> status(statusCode) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">typeof</span> statusCode !== <span class="string">'number'</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'something wrong!'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.res.statusCode = statusCode;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">以上代码实现了对koa的status的读取和设置，读取的时候返回的是基于原生的response对象的statusCode属性，而body的读取则是对this._body进行读写和操作。这里对body进行操作并没有使用原生的this.res.end，因为在我们编写koa代码的时候，会对body进行多次的读取和修改，所以真正返回浏览器信息的操作是在application.js里进行封装和操作。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>第三步：这个时候我们可以通过ctx.request.url、ctx.request.path来取到值，但还是不够方便，我们想要实现ctx直接取值。这样我们利用context.js，将上面实现的那些方法直接挂载到ctx上面。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> proto = &#123;&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">delegateSet</span>(<span class="params">property, name</span>) </span>&#123;</span><br><span class="line">    proto.__defineSetter__(name, <span class="function"><span class="keyword">function</span> (<span class="params">val</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>[property][name] = val;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">delegateGet</span>(<span class="params">property, name</span>) </span>&#123;</span><br><span class="line">    proto.__defineGetter__(name, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>[property][name];</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> requestSet = [];</span><br><span class="line"><span class="keyword">let</span> requestGet = [<span class="string">'query'</span>];</span><br><span class="line"><span class="keyword">let</span> responseSet = [<span class="string">'body'</span>, <span class="string">'status'</span>];</span><br><span class="line"><span class="keyword">let</span> responseGet = responseSet;</span><br><span class="line">requestSet.forEach(<span class="function"><span class="params">ele</span> =&gt;</span> &#123;</span><br><span class="line">    delegateSet(<span class="string">'request'</span>, ele);</span><br><span class="line">&#125;);</span><br><span class="line">requestGet.forEach(<span class="function"><span class="params">ele</span> =&gt;</span> &#123;</span><br><span class="line">    delegateGet(<span class="string">'request'</span>, ele);</span><br><span class="line">&#125;);</span><br><span class="line">responseSet.forEach(<span class="function"><span class="params">ele</span> =&gt;</span> &#123;</span><br><span class="line">    delegateSet(<span class="string">'response'</span>, ele);</span><br><span class="line">&#125;);</span><br><span class="line">responseGet.forEach(<span class="function"><span class="params">ele</span> =&gt;</span> &#123;</span><br><span class="line">    delegateGet(<span class="string">'response'</span>, ele);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">module</span>.exports = proto;</span><br></pre></td></tr></table></figure>

<p>context.js文件主要是对常用的request和response方法进行挂载和代理，通过context.query直接代理了context.request.query，context.body和context.status代理了context.response.body与context.response.status。而context.request，context.response则会在application.js中挂载。</p>
<h3 id="模块三"><a href="#模块三" class="headerlink" title="模块三"></a>模块三</h3><p>目前为止我们已经成功实现了上下文context对象、 请求request对象和响应response对象模块，还差一个最重要的模块，就是<strong>koa的中间件模块</strong>，koa的中间件机制是一个剥洋葱式的模型，多个中间件通过use放进一个数组队列然后从外层开始执行，遇到next后进入队列中的下一个中间件，所有中间件执行完后开始回帧，执行队列中之前中间件中未执行的代码部分，这就是剥洋葱模型，koa的中间件机制。这样，开发者手中的请求数据会像仪仗队一样，乖乖的经过每一层中间件的检阅，最后响应给用户。既应付了复杂的操作，又避免了混乱的嵌套。除此之外，koa的中间件还支持异步，可以使用async/await。</p>
<p>第一步：<strong>让多个use的回调按照顺序排列成串</strong>。这里用到了数组和递归，每次use将当前函数存到一个数组中，最后按顺序执行。执行这一步用到一个<strong>compose</strong>函数，这个函数是重中之重。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">constructor</span> () &#123;</span><br><span class="line">    <span class="keyword">super</span>()</span><br><span class="line">    <span class="comment">// this.fn  改成：</span></span><br><span class="line">    <span class="keyword">this</span>.middlewares = [] <span class="comment">// 需要一个数组将每个中间件按顺序存放起来</span></span><br><span class="line">    <span class="keyword">this</span>.context = context</span><br><span class="line">    <span class="keyword">this</span>.request = request</span><br><span class="line">    <span class="keyword">this</span>.response = response</span><br><span class="line">&#125;</span><br><span class="line">use (fn) &#123;</span><br><span class="line">    <span class="comment">// this.fn = fn 改成：</span></span><br><span class="line">    <span class="keyword">this</span>.middlewares.push(fn) <span class="comment">// 每次use，把当前回调函数存进数组</span></span><br><span class="line">&#125;</span><br><span class="line">compose(middlewares, ctx)&#123; <span class="comment">// 简化版的compose，接收中间件数组、ctx对象作为参数</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">index</span>)</span>&#123; <span class="comment">// 利用递归函数将各中间件串联起来依次调用</span></span><br><span class="line">        <span class="keyword">if</span>(index === middlewares.length) <span class="keyword">return</span> <span class="comment">// 最后一次next不能执行，不然会报错</span></span><br><span class="line">        <span class="keyword">let</span> middleware = middlewares[index] <span class="comment">// 取当前应该被调用的函数</span></span><br><span class="line">        middleware(ctx, () =&gt; dispatch(index + <span class="number">1</span>)) <span class="comment">// 调用并传入ctx和下一个将被调用的函数，用户next()时执行该函数</span></span><br><span class="line">    &#125;</span><br><span class="line">    dispatch(<span class="number">0</span>)</span><br><span class="line">&#125;</span><br><span class="line">handleRequest(req,res)&#123;</span><br><span class="line">    res.statusCode = <span class="number">404</span></span><br><span class="line">    <span class="keyword">let</span> ctx = <span class="keyword">this</span>.createContext(req, res)</span><br><span class="line">    <span class="comment">// this.fn(ctx) 改成：</span></span><br><span class="line">    <span class="keyword">this</span>.compose(<span class="keyword">this</span>.middlewares, ctx) <span class="comment">// 调用compose，传入参数</span></span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">typeof</span> ctx.body == <span class="string">'object'</span>)&#123;</span><br><span class="line">        res.setHeader(<span class="string">'Content-Type'</span>, <span class="string">'application/json;charset=utf8'</span>)</span><br><span class="line">        res.end(<span class="built_in">JSON</span>.stringify(ctx.body))</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ctx.body <span class="keyword">instanceof</span> Stream)&#123;</span><br><span class="line">        ctx.body.pipe(res)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> ctx.body === <span class="string">'string'</span> || Buffer.isBuffer(ctx.body)) &#123;</span><br><span class="line">        res.setHeader(<span class="string">'Content-Type'</span>, <span class="string">'text/htmlcharset=utf8'</span>)</span><br><span class="line">        res.end(ctx.body)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res.end(<span class="string">'Not found'</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第二步：把每个回调包装成<a href="https://juejin.im/post/6844903583234834445" target="_blank" rel="noopener">Promise</a>以实现异步，并在调用时then。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">compose(middlewares, ctx)&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">dispatch</span>(<span class="params">index</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(index === middlewares.length) <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve() <span class="comment">// 若最后一个中间件，返回一个resolve的promise</span></span><br><span class="line">        <span class="keyword">let</span> middleware = middlewares[index]</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(middleware(ctx, () =&gt; dispatch(index + <span class="number">1</span>))) <span class="comment">// 用Promise.resolve把中间件包起来</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> dispatch(<span class="number">0</span>)</span><br><span class="line">&#125;</span><br><span class="line">handleRequest(req,res)&#123;</span><br><span class="line">    res.statusCode = <span class="number">404</span></span><br><span class="line">    <span class="keyword">let</span> ctx = <span class="keyword">this</span>.createContext(req, res)</span><br><span class="line">    <span class="keyword">let</span> fn = <span class="keyword">this</span>.compose(<span class="keyword">this</span>.middlewares, ctx)</span><br><span class="line">    fn.then(<span class="function"><span class="params">()</span> =&gt;</span> &#123; <span class="comment">// then了之后再进行判断</span></span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">typeof</span> ctx.body == <span class="string">'object'</span>)&#123;</span><br><span class="line">            res.setHeader(<span class="string">'Content-Type'</span>, <span class="string">'application/json;charset=utf8'</span>)</span><br><span class="line">            res.end(<span class="built_in">JSON</span>.stringify(ctx.body))</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ctx.body <span class="keyword">instanceof</span> Stream)&#123;</span><br><span class="line">            ctx.body.pipe(res)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> ctx.body === <span class="string">'string'</span> || Buffer.isBuffer(ctx.body)) &#123;</span><br><span class="line">            res.setHeader(<span class="string">'Content-Type'</span>, <span class="string">'text/htmlcharset=utf8'</span>)</span><br><span class="line">            res.end(ctx.body)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            res.end(<span class="string">'Not found'</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123; <span class="comment">// 监控错误发射error，用于app.on('error', (err) =&gt;&#123;&#125;)</span></span><br><span class="line">        <span class="keyword">this</span>.emit(<span class="string">'error'</span>, err)</span><br><span class="line">        res.statusCode = <span class="number">500</span></span><br><span class="line">        res.end(<span class="string">'server error'</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面是使用promise来封装的代码，后面用async和await可以让代码更加简洁。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">compose() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">async</span> ctx =&gt; &#123;</span><br><span class="line">            <span class="function"><span class="keyword">function</span> <span class="title">createNext</span>(<span class="params">middleware, oldNext</span>) </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">                    <span class="keyword">await</span> middleware(ctx, oldNext);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">let</span> len = <span class="keyword">this</span>.middlewares.length;</span><br><span class="line">            <span class="keyword">let</span> next = <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve();</span><br><span class="line">            &#125;;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">let</span> i = len - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">                <span class="keyword">let</span> currentMiddleware = <span class="keyword">this</span>.middlewares[i];</span><br><span class="line">                next = createNext(currentMiddleware, next);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">await</span> next();</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="模块四"><a href="#模块四" class="headerlink" title="模块四"></a>模块四</h3><p>要实现一个基础框架，<strong>错误处理和捕获</strong>必不可少，一个健壮的框架，必须保证在发生错误的时候，能够捕获到错误和抛出的异常，并反馈出来，将错误信息发送到监控系统上进行反馈。</p>
<p>我们如果想要捕获promise的错误，只需要使用promise的catch方法，就可以把所有的中间件的异常全部捕获到，现在我们已经实现了中间件的错误异常捕获，但是我们还缺少框架层发生错误的捕获机制，我们希望我们的服务器实例能有错误事件的监听机制，通过on的监听函数就能订阅和监听框架层面上的错误，实现这个机制不难，使用nodejs原生events模块即可，events模块给我们提供了事件监听on函数和事件触发emit行为函数，一个发射事件，一个负责接收事件，我们只需要将koa的构造函数继承events模块即可，继承了events模块后，当我们创建koa实例的时候，加上on监听函数，</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> EventEmitter = <span class="built_in">require</span>(<span class="string">'events'</span>);</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Application</span> <span class="keyword">extends</span> <span class="title">EventEmitter</span> </span>&#123;&#125;</span><br><span class="line"><span class="keyword">let</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"></span><br><span class="line">app.on(<span class="string">'error'</span>, err =&gt; &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'error happends: '</span>, err.stack);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>这样我们就实现了框架层面上的错误的捕获和监听机制了。总结一下，错误处理和捕获，分中间件的错误处理捕获和框架层的错误处理捕获，中间件的错误处理用promise的catch，框架层面的错误处理用nodejs的原生模块events，这样我们就可以把一个服务器实例上的所有的错误异常全部捕获到了。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/05/19/node/koa%E6%BA%90%E7%A0%81/" title="KOA源码">http://example.com/2021/05/19/node/koa源码/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Koa%E6%A1%86%E6%9E%B6/" rel="tag"># Koa框架</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/05/14/react/react%20hooks/" rel="prev" title="react hooks初学">
      <i class="fa fa-chevron-left"></i> react hooks初学
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/05/23/%E5%89%8D%E7%AB%AF/vue%E4%B8%8Ejs/" rel="next" title="AJAX与Js">
      AJAX与Js <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#KOA用法"><span class="nav-number">2.</span> <span class="nav-text">KOA用法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#listen"><span class="nav-number">2.1.</span> <span class="nav-text">listen</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ctx"><span class="nav-number">2.2.</span> <span class="nav-text">ctx</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#use"><span class="nav-number">2.3.</span> <span class="nav-text">use</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现思路"><span class="nav-number">2.4.</span> <span class="nav-text">实现思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#源码简介"><span class="nav-number">2.5.</span> <span class="nav-text">源码简介</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#application-js"><span class="nav-number">2.5.1.</span> <span class="nav-text">application.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#context-js"><span class="nav-number">2.5.2.</span> <span class="nav-text">context.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#request-js、response-js"><span class="nav-number">2.5.3.</span> <span class="nav-text">request.js、response.js</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#功能模块"><span class="nav-number">2.6.</span> <span class="nav-text">功能模块</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#模块一"><span class="nav-number">2.6.1.</span> <span class="nav-text">模块一</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模块二"><span class="nav-number">2.6.2.</span> <span class="nav-text">模块二</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模块三"><span class="nav-number">2.6.3.</span> <span class="nav-text">模块三</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模块四"><span class="nav-number">2.6.4.</span> <span class="nav-text">模块四</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

